package com.demo.config;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class ChannelInitializerImpl extends ChannelInitializer<SocketChannel> {

//    @Autowired
    private NettyServerHandler nettyServerHandler;

    @Autowired
    private SimpleChannelHandler simpleChannelHandler;

    @Autowired
    private ModbusTcpServerHandler modbusTcpServerHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 添加编解码器
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

        // 添加业务处理器
        pipeline.addLast("handler", modbusTcpServerHandler);
        // 在ChannelInitializerImpl中添加
//        pipeline.addLast("idleStateHandler",
//                new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
//        pipeline.addLast("heartbeatHandler", new HeartbeatHandler());

    }
}
